package ycl.important.service.impl.hovel;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ycl.important.common.constants.FileConstant;
import ycl.important.common.models.res.hovel.UploadRes;
import ycl.important.common.models.res.hovel.UploadVideoRes;
import ycl.important.common.utils.BeanConvertUtil;
import ycl.important.common.utils.VideoUtil;
import ycl.important.service.hovel.UploadService;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 *
 * @author: YCL
 * @date: 2021-09-02 12:45:39
 */
@Service("uploadService")
@Slf4j
public class UploadServiceImpl implements UploadService {


	private final String savePath = "D:/Java/upload/";//存储路径
	private final String visitPath = "D:/Java/upload/";//访问路径

	@Override
	public UploadVideoRes video(MultipartFile file, String folder) {
		UploadRes upload = upload(file, FileConstant.VIDEO_SUFFIX, folder);
		UploadVideoRes vo = BeanConvertUtil.convert(upload, UploadVideoRes.class);
		if (vo == null)
			return new UploadVideoRes();

		String imgName = IdUtil.fastSimpleUUID() + ".jpg";
		String imgUrl = visitPath + folder + "/" + imgName;
		String imgSaveUrl = savePath + folder + "/" + imgName;
		VideoUtil.getFrame(vo.getFileUrl(), imgSaveUrl);//获取视频首帧
		vo.setImgName(imgName)
				.setImgUrl(imgUrl);
		return vo;


		//new HashMap<>()
	}

	@Override
	public UploadRes images(MultipartFile file, String folder) {
		return upload(file, FileConstant.IMAGE_SUFFIX, folder);
	}

	/**
	 * 上传文件方法
	 *
	 * @param file     文件
	 * @param suffixes 后缀数组
	 * @param folder   保存的文件夹
	 * @return 上传的参数
	 */
	private UploadRes upload(
			MultipartFile file,
			String[] suffixes,
			String folder) {
		Assert.isFalse(file.isEmpty(), "文件不能为空");
		String relativeName = file.getOriginalFilename();//文件相对路径名
		String suffix = FileUtil.extName(relativeName);//后缀
		Assert.isTrue(ArrayUtil.containsIgnoreCase(suffixes, suffix), "文件格式不支持");

		String resFolder = "/" + folder + "/";
		String path = savePath + folder + "/";//存储位置
		String fileName = IdUtil.fastSimpleUUID() + "." + suffix;//文件名
		File video = new File(path, fileName);
		FileUtil.mkParentDirs(video);//创建文件夹
		try {
			file.transferTo(video);
			return new UploadRes()
					.setFileName(resFolder + fileName)
					.setFileUrl(path + fileName);
		} catch (IOException e) {
			log.error("文件上传异常");
		}
		return null;
	}


}
